//
//  ScrollBarView.swift
//  JTYP
//
//  Created by Groot on 2017/11/28.
//  Copyright © 2017年 inspur. All rights reserved.
//

@objc protocol ScrollBarViewDelegate: class {
    @objc optional func beginRefresh()
}

enum BarStyle {
    case scroll
    case average
}

class ScrollBarView: UIView {
    
    // 滑块动画时长
    static let SliderViewAnimateDuration: CGFloat = 0.2
    // 滑块高度
    static let SliderViewHeight: CGFloat = 2
    // 普通文本颜色
    public var normalTitleColor = UIColorFromRGB(rgbValue: 0x777777)
    // 选中文本颜色
    public var selectedTitleColor = UIColorFromRGB(rgbValue: 0xF77777) {
        didSet {
            sliderViewColor = selectedTitleColor
            sliderView.backgroundColor = sliderViewColor
        }
    }
    // 底部分割线颜色
    public var bottomLineColor = UIColorFromRGB(rgbValue: 0xF77777) {
        didSet {
            bottomLine.backgroundColor = bottomLineColor
        }
    }
    // scrollbar 高度
    public var scrollBarHeight:CGFloat = 44 {
        didSet {
            scrollBar.snp.remakeConstraints({ (make) in
                make.top.left.right.equalToSuperview()
                make.height.equalTo(scrollBarHeight)
            })
        }
    }
    // 字号
    public var scrollBarTitleFontSize: CGFloat = 16.0
    // 滑块颜色
    private var sliderViewColor = UIColorFromRGB(rgbValue: 0xF77777)

//    private var cellSize = CGSize.init(width: 60, height: self.scrollBarHeight)
    private var viewControllers:[UIViewController]?
    private var style: BarStyle = .scroll
    private var barItems: [ScrollBarItem]? {
        didSet {
            scrollBar.reloadData()
            scrollBar.layoutIfNeeded()
        }
    }
    private var selectedIndexPath: IndexPath?
    private var currentPage: Int? {
        didSet {
            let indexPath = IndexPath.init(row: currentPage!, section: 0)
            tabTo(indexPath, animated: true, isProactive: false)
        }
    }
    
    private lazy var collectionViewLayout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 8
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        //layout.itemSize = cellSize
        return layout;
    }()
    
    lazy var scrollBar: ScrollBar = { [unowned self] in
        
        var bar = ScrollBar.init(frame: .zero, collectionViewLayout: collectionViewLayout)
        bar.register(ScrollBarCell.self, forCellWithReuseIdentifier: ScrollBarCell.Identifier)
        bar.allowsMultipleSelection = false
        bar.showsHorizontalScrollIndicator = false
        bar.delegate = self
        bar.dataSource = self
        return bar
        
    }()
    
    lazy var bottomLine: UIView = {
        var v = UIView()
        v.backgroundColor = .clear
        return v
    }()
    
    private lazy var sliderView: UIView = {
        var view = UIView()
        view.backgroundColor = sliderViewColor
        return view
    }()
    
    private lazy var mainScrollView: UIScrollView = { [unowned self] in
        var scrollView = UIScrollView()
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        scrollView.delegate = self
        return scrollView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        customization()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        customization()
    }
    
    func customization() {
        // Scroll Bar
        addSubview(scrollBar)
        scrollBar.snp.makeConstraints({ (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(scrollBarHeight)
        })
        scrollBar.addSubview(sliderView)
        
        // bottomLine
        addSubview(bottomLine)
        bottomLine.snp.makeConstraints { (make) in
            make.top.equalTo(scrollBar.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }
        
        // Main ScrollView
        addSubview(mainScrollView)
        mainScrollView.snp.makeConstraints { (make) in
            make.top.equalTo(scrollBar.snp.bottom).offset(1)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().priority(.low)
        }
    }
    
    func updateScrollBarConstraints() {
        let cellSize = CGSize.init(width: scrollBar.frame.width / CGFloat(barItems?.count ?? 1), height: scrollBarHeight)
        collectionViewLayout.minimumLineSpacing = 0
        collectionViewLayout.itemSize = cellSize
        scrollBar.setCollectionViewLayout(collectionViewLayout, animated: false)
    }
    
    func setScrollBarItems(items: [ScrollBarItem],
                           and controllers: [UIViewController],
                           style: BarStyle) {
        guard items.count >= 0, items.count == controllers.count else {
            fatalError("ScrollBarItem 数量与Controller数量不匹配")
        }
        self.style = style
        self.viewControllers = controllers
        // 添加所有viewcontroller的View到mainScrollView
        let parentVC = self.viewController()
        for (index, vc) in viewControllers!.enumerated() {
            parentVC?.addChildViewController(vc)
            vc.view.frame = CGRect.init(x: CGFloat(index) * mainScrollView.frame.width, y: 0, width: mainScrollView.frame.width, height: mainScrollView.frame.height)
            mainScrollView.addSubview(vc.view)
        }
        
        mainScrollView.contentSize = CGSize.init(width: CGFloat(items.count) * self.frame.width, height: 0)
        
        self.barItems = items
        //self.currentPage = 0
        // 设置一下sliderview 的frame
        self.updateSliderViewLocation(.zero)
        // 不加延迟，导致collectionview 还没更新执行cellforitem
        let time: TimeInterval = 0.1
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {[unowned self] in
            self.currentPage = 0
        }
        if style == .average {
            updateScrollBarConstraints()
        }
    }
    
    func refreshCurrentPage() {
        guard let vc = viewControllers?[currentPage ?? 0], vc is ScrollBarViewDelegate else {
            return;
        }
        (vc as! ScrollBarViewDelegate).beginRefresh?()
    }
    
    func tabTo(_ indexPath: IndexPath, animated: Bool, isProactive: Bool) {
        if let selectedIP = selectedIndexPath {
            // 取消上一个对应的Item的选中状态
            let model = barItems?[selectedIP.row]
            model?.isSelected = false
        }
        // 重新选中
        let cell: ScrollBarCell = scrollBar.cellForItem(at: indexPath) as! ScrollBarCell
        scrollBar.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
        let model = barItems?[indexPath.row]
        model?.isSelected = false
        // 滚动到指定位置
//        scrollBar.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        selectedIndexPath = indexPath
        updateSliderViewWith(cell, animated: animated)

        if isProactive {
            mainScrollView.setContentOffset(CGPoint.init(x: CGFloat(indexPath.row) * self.bounds.size.width, y: 0), animated: false)
        }
    }
    
    // 更新下标线的位置
    func updateSliderViewWith(_ cell: ScrollBarCell, animated: Bool) {
        let convertRect: CGRect = cell.convert((cell.titleLab?.frame)!, to: scrollBar)
        let animateDuration = animated ? ScrollBarView.SliderViewAnimateDuration : 0.0
        UIView.animate(withDuration: TimeInterval(animateDuration)) {[unowned self] in
            self.updateSliderViewLocation(CGRect.init(x: convertRect.minX, y: self.scrollBar.frame.height - ScrollBarView.SliderViewHeight, width: convertRect.width, height: ScrollBarView.SliderViewHeight))
        }
    }
    
    func updateSliderViewLocation(_ rect: CGRect) {
        sliderView.frame = rect
    }
    
    func setCurrentPage(_ page: Int) {
        self.currentPage = page
        
        let indexPath = IndexPath.init(row: currentPage ?? 0, section: 0)
        tabTo(indexPath, animated: true, isProactive: false)
    }
}

extension ScrollBarView:  UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell: ScrollBarCell = collectionView.dequeueReusableCell(withReuseIdentifier: ScrollBarCell.Identifier, for: indexPath) as? ScrollBarCell else {
            fatalError("UICollectionViewCell should be or extend from ScrollBarCell")
        }
        let barItem = barItems?[indexPath.row]
        cell.updateCellWithItem(barItem!)
        cell.setTitleColor(normal: normalTitleColor, selected: selectedTitleColor)
        cell.setTitleSize(fontSize: scrollBarTitleFontSize)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return barItems?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        tabTo(indexPath, animated: true, isProactive: true)
    }
}

extension ScrollBarView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView == mainScrollView {
            let scrollContentOffsetX = scrollView.contentOffset.x
            let tempCurrentPage = lroundf(Float(scrollContentOffsetX / self.frame.width))
            if tempCurrentPage != currentPage {
                currentPage = tempCurrentPage
            }
        }
    }
}

extension UIView {
    
    public func viewController()->UIViewController? {
        
        var nextResponder: UIResponder? = self
        
        repeat {
            nextResponder = nextResponder?.next
            
            if let viewController = nextResponder as? UIViewController {
                return viewController
            }
            
        } while nextResponder != nil
        
        return nil
    }
    
}


